/*
 * Copyright 1999-2015 dangdang.com.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * </p>
 */

package com.bicon.botu.mall.order.processor.task.schedule;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.mall.base.rpc.service.SystemConfigRpcService;
import com.bicon.botu.mall.order.cache.RedisLock;
import com.bicon.botu.mall.order.common.ConfirmEnum;
import com.bicon.botu.mall.order.common.OrderConstans;
import com.bicon.botu.mall.order.dto.MallConfigDto;
import com.bicon.botu.mall.order.entity.AfterSalesRecords;
import com.bicon.botu.mall.order.service.IAfterSalesRecordsService;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 退款退货自动确认收货
 * @author  jwj
 * @date    2018-06-21
 */
@Slf4j
//@ElasticJobConf(name = "ConfirmAfterSalesJob")
public class ConfirmAfterSalesJob implements SimpleJob {

    private static final String lock = "confirm_order_task_lock";

    @Autowired
    private RedisLock redisLock;

    @Autowired
    private SystemConfigRpcService systemConfigRpcService;

    @Autowired
    private IAfterSalesRecordsService iAfterSalesRecordsService;

    @Override
    public void execute(final ShardingContext shardingContext) {
        long lockTimeOut = redisLock.lock(lock,6000);
        String params = shardingContext.getShardingParameter();
        if (lockTimeOut <= 0) {
            log.info("自动同意售后申请分片：" + params + ",上一次任务未执行完毕");
            return;
        }
        BaseResult baseResult = systemConfigRpcService.getOderConfigValue(OrderConstans.AFTER_SALE_AFFIRM);
        log.info("分片：" + params + ",获取自动同意售后申请的配置：" + JSONObject.toJSONString(baseResult));
        if (baseResult.getCode() == Constants.RESPONSE_CODE_200) {
            MallConfigDto mallConfigDto = JSONObject.parseObject(JSONObject.toJSONString(baseResult.getData()), MallConfigDto.class);
            int timeLength = ConfirmEnum.valueOf(mallConfigDto.getDictionaryValue()).getTimeLength();
            if (timeLength > 0) {
                List<AfterSalesRecords> afterSalesRecords = new AfterSalesRecords().selectList(new EntityWrapper<AfterSalesRecords>().eq("status", OrderConstans.ORDER_AFTER_SALES_STATUS_3).eq("type", OrderConstans.ORDER_AFTER_SALES_type_2)
                        .eq("logic_delete", Constants.DEL_LOGIC_NORMAL).andNew("TIMESTAMPDIFF(DAY, update_date, now()) > {0}", timeLength));
                int num = 0;
                int errorNum = 0;
                log.info("分片：" + params + ",售后商家自动确认收货");
                for(AfterSalesRecords record : afterSalesRecords) {
                    try {
                        iAfterSalesRecordsService.receivedGoods("系统", record.getId());
                        num++;
                    } catch (Exception e) {
                        log.error(e.getMessage());
                        errorNum++;
                    }
                }
                log.info("售后商家自动确认收货分片：" + params + ",成功处理：" + num + ", 出现错误:" + errorNum);
            }
        }
        // 释放锁
        redisLock.releaseLock(lock,lockTimeOut);
    }
}
